package com.wisezone.studentmanger.listener;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class DemoServletContextListener implements ServletContextListener {
	private static final String url = "jdbc:mysql://localhost:3306/studentsystemdb";
	private static final String user = "root";
	private static final String password = "123";
	private Connection connection = null;

	public void contextDestroyed(ServletContextEvent arg0) {
		System.out.println("contextDestroyed ....");
		if (connection != null) {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public void contextInitialized(ServletContextEvent arg0) {
		System.out.println("contextInitialized ...");
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		try {
			connection = DriverManager.getConnection(url, user, password);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		ServletContext application = arg0.getServletContext();
		application.setAttribute("conn", connection);
		
	}

}
